using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PietschSoft.VE;

namespace SecurityLinkUp
{
    public partial class Meetings : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // before we do anything, ensure that the user has the right
            // role to perform anything on this page
            Security.CheckAdminUser(this);

            if (!Page.IsPostBack)
            {
                // only display the admin button for super admins
                if (Roles.IsUserInRole("SuperAdmin"))
                {
                    AdminModeChk.Visible = true;
                }

                // initially set operation buttons to disabled
                AddMeetingBtn.Enabled = false;
                DelMeetingBtn.Enabled = false;
                SaveMeetingBtn.Enabled = false;

                DrawDisplay();   
            }
        }

        protected void DrawDisplay()
        {
            // populate the list with chapers
            ChapterList.Items.Clear();
            ArrayList chapters;
            if (!AdminModeChk.Checked)
            {
                // only show chapters where the user is an admin
                //chapters = ChapterData.GetUserAdminChapters(Membership.GetUser().ProviderUserKey.ToString());
                // DEBUG: For debugging, let's just show all chapters
                chapters = ChapterData.GetChapters(CommonData.Status.ACTIVE);
            }
            else
            {
                // super admin mode - show all communities
                chapters = ChapterData.GetChapters(CommonData.Status.ACTIVE);
            }
            ChapterList.Items.Add("");
            foreach (Chapter c in chapters)
            {
                ListItem itm = new ListItem(c.name, c.uid.ToString());
                ChapterList.Items.Add(itm);
            }
        }


        protected void ChapterList_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisplayMeetings();
        }

        protected void DisplayMeetings ()
        {
            // clear the meetings list
            MeetingsList.Items.Clear();

            if (ChapterList.SelectedValue != "")
            {
                // populate the current meetings
                ArrayList meetings = MeetingData.GetAllChapterMeetings(new Guid(ChapterList.SelectedValue));
                foreach (Meeting m in meetings)
                {
                    ListItem itm = new ListItem("[" + m.Start.ToShortDateString() + "] - " + m.Title, m.uid.ToString());
                    MeetingsList.Items.Add(itm);
                }

                // select the first meeting if there is one
                if (meetings.Count > 0)
                {
                    MeetingsList.SelectedIndex = 0;
                    MeetingsList_SelectedIndexChanged(null, null);
                    SaveMeetingBtn.Enabled = true;
                }
                else
                {
                    ClearData();
                    SaveMeetingBtn.Enabled = false;
                }

                // enable the add meeting button
                AddMeetingBtn.Enabled = true;
            }
            else
            {
                // we dont have a chapter selected, so clear the display and
                // disable buttons
                ClearData();
                AddMeetingBtn.Enabled = false;
                DelMeetingBtn.Enabled = false;
                SaveMeetingBtn.Enabled = false;
            }
        }

        protected void AdminModeChk_CheckedChanged(object sender, EventArgs e)
        {
            DrawDisplay();
        }

        protected void MeetingsList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // get the meeting info and populate the form
            ClearData();
            Meeting m = MeetingData.GetMeeting(new Guid(MeetingsList.SelectedValue));
            if (m != null)
            {
                StartDate.Text = m.Start.ToShortDateString();
                StartTime.Text = m.Start.ToLongTimeString();
                EndDate.Text = m.End.ToShortDateString();
                EndTime.Text = m.End.ToLongTimeString();

                // populate the organizer dropdown with chapter admins
                Organizer.Items.Clear();
                SortedList chapteradmins = ChapterData.GetChapterAdmins(new Guid(ChapterList.SelectedValue));
                IDictionaryEnumerator itr = chapteradmins.GetEnumerator();
                while (itr.MoveNext())
                {
                    User u = (User)itr.Value;

                    ListItem usritm = new ListItem(u.name, u.uid.ToString());
                    Organizer.Items.Add(usritm);
                }

                // make the right user selected
                ListItem organizer = Organizer.Items.FindByValue(m.OrganizerID.ToString());
                organizer.Selected = true;
                
                MeetingTitle.Text = m.Title;
                Description.Text = m.Description;
                Location.Text = m.Location;
                AdditonalInfo.Text = m.AdditionalInfo;
                if (m.HasPosition)
                {
                    // clear the map and add a pushpin
                    Map.Pushpins.Clear();
                    LatLong Position = new LatLong(m.geolat, m.geolong);
                    Pushpin p = new PietschSoft.VE.Pushpin(m.uid.ToString(), Position, null, m.Location, "");
                    Map.Pushpins.Add(p);
                    Map.Latitude = m.geolat;
                    Map.Longitude = m.geolong;
                    Map.Zoom = 14;

                    // set the form data
                    GeoLat.Value = m.geolat.ToString();
                    GeoLong.Value = m.geolong.ToString();
                    LocationStatusImg.ImageUrl = "~/Images/check.png";
                }
                else
                {
                    // clear the map and set the form data
                    Map.Pushpins.Clear();
                    Map.Latitude = 0;
                    Map.Longitude = 0;
                    Map.Zoom = 0;
                    GeoLat.Value = "";
                    GeoLong.Value = "";
                    LocationStatusImg.ImageUrl = "~/Images/cross.png";
                }

                // set the presentations link
                string presentationstats = GetPresentationStats(m.uid);
                PresentationsLink.Text = presentationstats;
                PresentationsLink.NavigateUrl = "/admin/presentations.aspx?meetingid=" + m.uid;
                PresentationsLink.Visible = true;

                // enable the save meeting button
                SaveMeetingBtn.Enabled = true;

                // we should have a selected meeting, so enable the del meetings button
                DelMeetingBtn.Enabled = true;
            }
        }

        protected string GetPresentationStats(Guid meetingid)
        {
            int accepted = 0;
     
            ArrayList presentations = MeetingData.GetMeetingPresentations(meetingid);
            foreach (Presentation p in presentations)
            {
                if (p.accepted)
                {
                    accepted++;
                }
            }

            return presentations.Count + " presentations submitted - " + accepted + " accepted.";
        }

        protected void AddMeetingBtn_Click(object sender, ImageClickEventArgs e)
        {
            // Clear the old data
            ClearData();

            // add a temporary item to the current meetings, and make it selected
            MeetingsList.SelectedIndex = -1;
            Guid uid = Guid.NewGuid();
            ListItem itm = new ListItem("New Meeting", uid.ToString());
            itm.Selected = true;
            MeetingsList.Items.Add(itm);

            // populate the organizer dropdown with chapter admins
            Organizer.Items.Clear();
            SortedList chapteradmins = ChapterData.GetChapterAdmins(new Guid(ChapterList.SelectedValue));
            IDictionaryEnumerator itr = chapteradmins.GetEnumerator();
            while (itr.MoveNext())
            {
                User u = (User)itr.Value;

                ListItem usritm = new ListItem(u.name, u.uid.ToString());
                Organizer.Items.Add(usritm);
            }

            // enable the save meeting button
            SaveMeetingBtn.Enabled = true;

        }


        protected void SaveMeetingBtn_Click(object sender, EventArgs e)
        {
            // validate the start and end times
            DateTime stime;
            DateTime etime;
            try
            {
                stime = DateTime.Parse(StartDate.Text + " " + StartTime.Text);
            }
            catch (FormatException fex)
            {
                ErrorMessage.Text = "Invalid start date/time";
                return;
            }
            try
            {
                etime = DateTime.Parse(EndDate.Text + " " + EndTime.Text);
            }
            catch (FormatException fex)
            {
                ErrorMessage.Text = "Invalid end date/time";
                return;
            }

            // check that start is before end
            if (stime > etime)
            {
                ErrorMessage.Text = "The start date/time must be before the end date/time";
                return;
            }

            // Create a new meeting
            Meeting m = new Meeting(new Guid(MeetingsList.SelectedValue), new Guid(ChapterList.SelectedValue), stime, etime, MeetingTitle.Text, Description.Text, new Guid(Organizer.SelectedValue), Location.Text, AdditonalInfo.Text);

            // if there's a geo location, add the details to the meeting
            if ((GeoLat.Value != "") && (GeoLong.Value != ""))
            {
                m.SetGeoData(double.Parse(GeoLat.Value), double.Parse(GeoLong.Value));
            }

            // save the meeting to the database
            string result = MeetingData.SaveMeetingToDB(m);
            if (result == "")
            {
                ErrorMessage.Text = "Successfully saved.";
                
                // reload the meetings list to show the added meeting
                DisplayMeetings();
            }
            else
            {
                ErrorMessage.Text = result;
            }          
        }

        
        protected void ConfirmDeleteBtn_Click(object sender, EventArgs e)
        {
            bool ok = MeetingData.DeleteMeeting(new Guid(MeetingsList.SelectedValue));
            if (ok)
            {
                ErrorMessage.Text = "Meeting Deleted";
                DisplayMeetings();
            }
            else
            {
                ErrorMessage.Text = "Error Deleting Meeting";
            }
        }

        protected void ClearData()
        {
            StartDate.Text = "";
            StartTime.Text = "";
            EndDate.Text = "";
            EndTime.Text = "";
            MeetingTitle.Text = "";
            Description.Text = "";
            Location.Text = "";
            AdditonalInfo.Text = "";
            LocationStatusImg.ImageUrl = "~/Images/cross.png";
            GeoLat.Value = "";
            GeoLong.Value = "";
            PresentationsLink.Visible = false;
            ErrorMessage.Text = "";
        }

 
    }
}
